<template>
  <div>
    <title-panel />
    <van-form
      input-align="right"
      error-message-align="right"
      :show-error-message="false"
      show-error
      scroll-to-error
      validate-first
      @failed="onFailed"
      @submit="onSubmit"
    >
      <van-field
        readonly
        :value="obj.operationDate"
        name="operationDate"
        label="操作日期"
        input-align="right"
        required
      />
      <van-field
        readonly
        name="cultureArea"
        label="转入养殖区域"
        :value="cultureArea"
        is-link
        required
        placeholder="请选择"
        input-align="right"
        :rules="[{ required: true, message: '请选择转入养殖区域' }]"
        @click="natureShows = true"
      />
      <van-popup v-if="!isDisabled" v-model="natureShows" position="bottom">
        <van-picker
          show-toolbar
          :columns="dataLiat"
          value-key="cultureArea"
          @confirm="onConfirmType"
          @cancel="natureShows = false"
        />
      </van-popup>

      <van-field
        name="currentDays"
        label="当前天数"
        v-model="obj.currentDays"
        required
        type="digit"
        placeholder="请输入整数"
        input-align="right"
        :rules="[{ required: true, message: '请输入当前天数' }]"
      />

      <van-cell class="btnfrom" :border="false">
        <van-field
          :border="false"
          class="fromInput"
          readonly
          required
          name="changeNum"
          label="羊只数量(只)"
          :value="obj.changeNum"
          label-width="40%"
          placeholder="请选择"
          input-align="right"
          :rules="[{ required: true, message: '请完善羊只数量' }]"
          @click="chooseEarLabel"
        />
        <van-button native-type="button" plain color="#37B5B5" class="addbtn" @click="scanClick()" type="primary"
          >扫一扫</van-button
        >
      </van-cell>
      <div class="spacing" />
      <div class="add-btn">
        <van-button
          block
          type="info"
          color="#37B5B5"
          style="width: 85%; margin: auto; margin-top: 50px"
          native-type="submit"
          size="large"
          :loading="loading"
          loading-text="提交中..."
          >保存</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  Calendar,
  RadioGroup,
  Radio,
  Dialog,
  Toast,
  DatetimePicker,
  Picker,
  Button,
  Icon,
  Popup,
  Cell
} from 'vant'
import TitlePanel from '@/components/titlePanel'
import dayjs from 'dayjs'
import { getValue, setValue, clearValue } from '@/utils/auth'
import { getHandle, postHandle } from '../../api'
export default {
  components: {
    TitlePanel,
    [Form.name]: Form,
    [Field.name]: Field,
    [Calendar.name]: Calendar,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Picker.name]: Picker,
    [DatetimePicker.name]: DatetimePicker,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    [Cell.name]: Cell,
    [Dialog.Component.name]: Dialog.Component
  },
  data() {
    return {
      loading: false,
      flag: true,
      isDisabled: false,
      natureShows: false,
      natureShow: false,
      cultureArea: '',
      startDays: '',
      endDays: '',
      sex: '',
      obj: {
        operationDate: new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate(),
        stageId: '',
        currentDays: '',
        changeNum: getValue('earTag2') ? JSON.parse(getValue('earTag2')).length : '',
        individualInfoIds: getValue('earTag2') ? JSON.parse(getValue('earTag2')) : []
      },
      type: null,
      dataLiat: []
    }
  },
  created() {
    this.getUnitList()
  },
  mounted() {
    this.$bridge.register('backScanData', data => {
      if (JSON.parse(data).individualId) {
        let arr = [JSON.parse(data).individualId]
        setValue('earTag2', JSON.stringify(arr))
        this.obj.changeNum = 1
        this.obj.individualInfoIds = arr
      } else {
        Toast('羊只信息未录入')
      }
    })

    this.$bridge.register('refresh', data => {
      this.obj.changeNum = JSON.parse(getValue('earTag2')).length
      this.obj.individualInfoIds = getValue('earTag2') ? JSON.parse(getValue('earTag2')) : []
    })
  },
  methods: {
    scanClick() {
      this.$bridge.call('base.scanOneScan')
    },
    // 选择养殖区域
    onConfirmType(value) {
      this.obj.stageId = value.id
      this.cultureArea = value.cultureArea
      this.startDays = value.startDays
      this.endDays = value.endDays
      this.sex = value.sex
      this.natureShows = false
    },

    // 新增跳转选择耳标
    chooseEarLabel() {
      // 跳转耳标选择之前缓存已经填写好的数据
      // 选择完耳标之后回显已经填写好的数据
      if (this.sex !== '') {
        if (this.sex === '公母') {
          setValue('fzmSex', '')
        } else {
          setValue('fzmSex', this.sex)
        }

        this.$bridge.call('addCheckEarTag2')
      } else {
        Toast('请选择转入养殖区域')
      }
    },
    // 根据舍ID查询所有阶段数据
    getUnitList() {
      getHandle('/agri/api/yzbzh/breedAreaChange/queryStageList', { houseInfoId: getValue('fzmHourseId') }).then(
        res => {
          res.data.rows.map((item, index) => {
            const objs = {
              id: '',
              cultureArea: '',
              sex: '',
              startDays: '',
              endDays: ''
            }
            for (var key in item) {
              objs.id = item.id
              objs.cultureArea = item.cultureArea + item.physiologyStageShow
              objs.sex = item.sex
              objs.startDays = item.startDays
              objs.endDays = item.endDays
            }
            this.dataLiat.push(objs)
          })
        }
      )
    },

    onFailed(errorInfo) {
      Toast(errorInfo.errors[0].message)
    },
    onSubmit(value) {
      this.onSave()
    },
    onSave() {
      if (this.endDays === '' || this.endDays === null) {
        if (this.obj.currentDays < this.startDays) {
          Toast('请输入养殖区域内的正确天数')
          return
        }
      } else {
        if (this.obj.currentDays < this.startDays) {
          Toast('请输入养殖区域内的正确天数')
          return
        }
        if (this.obj.currentDays > this.endDays) {
          Toast('请输入养殖区域内的正确天数')
          return
        }
      }
      this.loading = true
      const params = {
        operationDate: this.obj.operationDate,
        currentDays: this.obj.currentDays,
        changeNum: this.obj.changeNum,
        stageId: this.obj.stageId,
        individualInfoIds: getValue('earTag2') ? JSON.parse(getValue('earTag2')) : [],
        houseInfoId: getValue('fzmHourseId') || '',
        subjectInfoId: getValue('subjectInfoId'),
        tenantCode: getValue('tenantCode'),
        callChannel: getValue('callChannel'),
        loginUserId: getValue('loginUserId')
      }
      postHandle('/agri/api/yzbzh/breedAreaChange/save', params).then(res => {
        console.log(res)
        // 新增成功跳转列表页
        if (res.status == 0) {
          Toast.success('操作成功')
          // 清除本地耳标信息缓存
          clearValue('earTag2')
          // // 清除缓存的回显信息
          this.loading = false
          clearValue('fzmSex')
          this.$bridge.call('base.closePage')
        } else {
          Toast.fail(res.msg || '操作失败')
          this.loading = false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.tip {
  padding-top: 15px;
  color: #999999;
  font-size: 12px;
  line-height: 16px;
  margin: auto;
}
.btn {
  width: 80%;
  margin: 50px auto 0 auto;
}
.btn > div {
  height: 50px;
  background: #2871fe;
  border-radius: 4px;
  text-align: center;
  line-height: 50px;
  color: #ffffff;
  font-size: 17px;
}
.btn .cancel {
  margin-top: 20px;
  background: rgba(40, 113, 254, 0.1);
  border: 1px solid #2871fe;
  color: #2871fe;
}
::v-deep .van-field__label {
  width: 6em;
}
.bthStyle {
  width: 56px;
  height: 20px;
  border-radius: 10px;
  border: 1px solid #2871fe;
}
.active {
  background-color: #fff;
  color: #2871fe;
}
.add-btn {
  padding-bottom: 20px;
}
.addbtn {
  width: 50px;
  height: 24px;
  font-size: 13px;
  padding: 0;
  margin-right: 13px;
  z-index: 10;
  float: right;
  margin-top: -38px;
}
.btnfrom {
  padding: 1px 0;
}
.fromInput {
  width: 86%;
}
</style>
